package ooday03;

/**
 * 多态的测试类
 */
    public class PolymorghicDemo {
        public static void main(String[] args) {
            //演示强转成功的条件
           /*
           Animal o = new Dog("小黑",1,"黑");
            Dog g = (Dog) o;
            Swim s = (Swim) o;
            //  Fish f = (Fish) o;  运行时会发生ClassCastException类型转换异常

            System.out.println( o instanceof  Dog);  //true
            System.out.println( o instanceof  Swim);  //true
            System.out.println( o instanceof  Fish);  //false
            if( o instanceof  Fish){
                Fish f = (Fish) o;
            }
            */



        //演示向上造型（多态）的第2点应用：
        //  Animal o = new Animal();  编译错误，抽象类不能被实例化
        Animal[] animal = new Animal[5];
        animal[0] = new Dog("小黑",2,"黑");
        animal[1] = new Dog("小白",1,"白");
        animal[2] = new Fish("小金",2,"金");
        animal[3] = new Fish("小花",2,"花");
        animal [4] = new Chick("小灰",3,"灰");

        for (int i = 0; i < animal.length; i++) {
            System.out.println(animal[i].name);  //输出每个动物的名字
            animal[i].drink();  //每个动物喝水
            animal[i].eat();  //每个动物吃饭

            //  狗看家/游泳/鸡下蛋
            if(animal[i] instanceof  Dog){
                Dog dog = (Dog)animal[i];
                dog.lookHome();
            }
            if(animal[i] instanceof Chick){
                Chick chick = (Chick) animal[i];
                chick.layEggs();
            }
            if(animal[i] instanceof Swim){   //适用于所有实现Swim接口的（会游泳的）
                Swim s = (Swim) animal[i];
                s.swim();
            }
        }

        //演示向上造型（多态）的第1点应用
       /*
       Master master = new Master();

       //  Animal dog = new Dog("小黑",2,"黑");
        //  Animal chick = new Chick("小花",3,"花");
          //  Animal fish = new Fish("小金",1,"金");

        Dog dog = new Dog("小黑",2,"黑");
        Chick chick = new Chick("小花",3,"花");
        Fish fish = new Fish("小金",1,"金");

        //重写被调一定看对象，对象是谁就走谁
        master.feed(dog);      //在传参的同时系统自动做了向上造型
        master.feed(chick);
        master.feed(fish);
        */

        //演示向上造型的语法：
       /*
       Dog o1 = new Dog("小黑",2,"黑");
        // o1.name/age/color/drink()/eat()/swim()/lookHome();
        Animal o2 =  new Dog("小黑",2,"黑");
        // o2. name/age/color/drink()/eat();
        Swim o3 =  new Dog("小黑",2,"黑");
        // o3.swim;
        */
    }
}